/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.firebird.base.orm.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import com.firebird.base.domain.Page;

/**
 * @author qiuxj
 * @date 2009-11-14
 */
public class PagedRowMapperResultSetExtractor implements ResultSetExtractor {

	  private final RowMapper rowMapper;
	  private final int pageNo;
	  private final int pageSize;
	  private final int totalCount;

	  public PagedRowMapperResultSetExtractor(RowMapper rowMapper, int totalCount)
	  {
	    this.rowMapper = rowMapper;
	    this.pageNo = 1;
	    this.pageSize = 15;
	    this.totalCount = totalCount;
	  }

	  public PagedRowMapperResultSetExtractor(RowMapper rowMapper, int pageNo, int pageSize, int totalCount) {
	    this.rowMapper = rowMapper;
	    this.pageNo = pageNo;
	    this.pageSize = pageSize;
	    this.totalCount = totalCount;
	  }

	  public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
	    if (this.totalCount < 1) {
	      return new Page();
	    }
	    List results = new ArrayList(this.pageSize);
	    int startIndex = Page.getStartOfPage(this.pageNo, this.pageSize);
	    int rowNum = 0;
	    rs.absolute(startIndex);
	    while ((rs.next()) && (rowNum < this.pageSize)) {
	      results.add(this.rowMapper.mapRow(rs, startIndex + rowNum++));
	    }
	    return new Page(results, startIndex, this.totalCount, this.pageSize);
	  }

}
